package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.UserLocation;
import com.itheima.service.mongo.UserLocationService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class UserLocationServiceImpl implements UserLocationService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void save(Double longitude, Double latitude, String addrStr, Long userId) {
        //1.通过用户id查询用户地址位置
        UserLocation userLocation = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class);

        //2.判断地址是否为空
        if (userLocation == null) {
            //2.1若为空,保存
            userLocation = new UserLocation();

            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userLocation.setAddress(addrStr);

            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
        }else{
            //2.2若不为空,更新
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userLocation.setAddress(addrStr);
            userLocation.setLastUpdated(userLocation.getUpdated());
            userLocation.setUpdated(System.currentTimeMillis());
        }

        mongoTemplate.save(userLocation);
    }

    @Override
    public List<Long> searchNear(Long userId, Long distance) {
        //1.查询我的坐标
        UserLocation userLocation = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class);

        //2.创建条件对象,以我的坐标为圆心,以距离为半径,搜索圈里面的用户地址list
        GeoJsonPoint point = userLocation.getLocation();
        Distance radius = new Distance(distance / 1000, Metrics.KILOMETERS);
        Circle circle = new Circle(point,radius);

        Query query = new Query(Criteria.where("location").withinSphere(circle));

        //3.遍历用户地址list.获取每个用户id,将id放入一个idList中,
        List<UserLocation> userLocations = mongoTemplate.find(query, UserLocation.class);
        List<Long> idList = userLocations.stream().map(UserLocation::getUserId).collect(Collectors.toList());
        //4.返回idList
        return idList;
    }
}
